import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { PurchaseService } from './../../../@core/services/purchase/purchase.service';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import {
  DataTableComponent,
  DialogService,
  DrawerService,
  IDrawerOpenResult,
  TableWidthConfig,
} from 'ng-devui';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { environment } from 'src/environments/environment';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { DisApprovalReasonComponent } from '../dis-approval-reason/dis-approval-reason.component';
import { ReviewDocComponent } from '../../basic-data/user-center/review-doc/review-doc.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
@Component({
  selector: 'app-purchase-requirement',
  templateUrl: './purchase-requirement.component.html',
  styleUrls: ['./purchase-requirement.component.scss'],
})
export class PurchaseRequirementComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20,
  };
  results: IDrawerOpenResult;
  pageSizeOptions = [10, 20, 30, 50, 100];
  tableData = [];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '操作',
        fieldType: 'text',
        fixedLeft: '80px',
      },
      {
        field: 'name',
        header: '采购需求单号',
        fieldType: 'text',
        fixedLeft: '430px',
      },
      {
        field: '申请人',
        header: '申请人',
        fieldType: 'text',
      },
      {
        field: '申请部门',
        header: '申请部门',
        fieldType: 'text',
      },

      {
        field: '建议采购时间',
        header: '建议采购时间',
        fieldType: 'text',
      },
      {
        field: '是否结案',
        header: '是否结案',
        fieldType: 'text',
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: '附件',
        header: '附件',
        fieldType: 'text',
      },
      {
        field: '二维码',
        header: '二维码',
        fieldType: 'text',
      },
      {
        field: '制单人',
        header: '制单人',
        fieldType: 'text',
      },
      {
        field: '制单日期',
        header: '制单日期',
        fieldType: 'text',
      },
      {
        field: '日志',
        header: '日志',
        fieldType: 'text',
      },
      {
        field: '状态',
        header: '状态',
        fieldType: 'text',
        fixedRight: '0px',
      },
    ],
  }; //表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px',
    },
    {
      field: '操作',
      width: '350px',
    },
    {
      field: '采购需求单号',
      width: '200px',
    },
    {
      field: '申请人',
      width: '150px',
    },
    {
      field: '申请部门',
      width: '170px',
    },
    {
      field: '建议采购时间',
      width: '170px',
    },
    {
      field: '是否结案',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
    {
      field: '附件',
      width: '150px',
    },
    {
      field: '二维码',
      width: '150px',
    },
    {
      field: '制单人',
      width: '150px',
    },
    {
      field: '制单日期',
      width: '150px',
    },
    {
      field: '日志',
      width: '150px',
    },
    {
      field: '状态',
      width: '150px',
    },
  ]; //表格宽度配置
  dataTableOptions2 = {
    columns: [
      {
        field: 'code',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '物料规格',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '是否结案',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料单位',
        fieldType: 'text',
        fixedLeft: '450px',
      },
      {
        field: 'workCode',
        header: '申请采购数量',
        fieldType: 'text',
      },
      {
        field: 'workCode',
        header: '建议采购时间',
        fieldType: 'text',
      },
      {
        field: 'workCode',
        header: '建议供应商',
        fieldType: 'text',
      },
      {
        field: 'workCode',
        header: '备注',
        fieldType: 'text',
      },
    ],
  }; //表头数据
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '150px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料规格',
      width: '150px',
    },
    {
      field: '是否结案',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '物料单位',
      width: '150px',
    },
    {
      field: '申请采购数量',
      width: '150px',
    },
    {
      field: '建议采购时间',
      width: '150px',
    },
    {
      field: '已采购数量',
      width: '150px',
    },
    {
      field: '建议供应商',
      width: '150px',
    },
    {
      field: '建议供应商',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
  ]; //表格宽度配置
  msgs: { severity: any; summary: any; content: any }[];
  fifter = {
    PageSize: 20,
    PageNumber: 1,
    StartTime: '',
    EndTime: '',
    PurchaseRequiredNum: '',
    PartNumPartName: '',
    PurchaseManNumPurchaseManName: '',
    Status: '',
    isClosed: null,
  };
  status = ['全部', '未开始审核', '审核通过', '审核中'];
  splitBarSize = '0px';
  partDetailHeight = '100%';
  date: any = [];
  @ViewChild(DataTableComponent, { static: true })
  datatable: DataTableComponent;
  checkedIds: any = [];
  partDetail: any = [];
  selectedRowIndex: any;
  showDetailId: any;
  checkedCodes: any = [];
  constructor(
    private SharedMethodService: SharedMethodService,
    private Router: Router,
    private DialogService: DialogService,
    private drawerService: DrawerService,
    private dataSharingService: DataSharingService,
    private PurchaseService: PurchaseService,
    private dialogService: DialogService,
    private ReviewRolesService: ReviewRolesService
  ) {}
  ngOnInit(): void {
    this.filter();
  }
  // 顶部打印：仅允许勾选一条采购需求单
  printSelected(): void {
    const rows = this.CheckedRows || [];
    if (!rows.length) {
      this.showToast('warn', '提示', '请勾选一条采购需求单');
      return;
    }
    if (rows.length !== 1) {
      this.showToast('warn', '提示', '一次只能打印一条采购需求单');
      return;
    }
    const row = rows[0];
    const html = this.buildPrintHtml(row);
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow?.document as Document | undefined;
    if (!doc) {
      document.body.removeChild(iframe);
      this.showToast('error', '错误', '无法初始化打印窗口');
      return;
    }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } finally {
        setTimeout(() => {
          if (iframe && iframe.parentNode) {
            iframe.parentNode.removeChild(iframe);
          }
        }, 400);
      }
    }, 200);
  }

  // 构建采购需求单打印模板（抬头信息 + 明细 + 合计 + 二维码列）
  private buildPrintHtml(order: any): string {
    const parts = order?.purchaseRequiredOrderParts || [];
    const toNum = (x: any) => { const n = Number(x); return isNaN(n) ? 0 : n; };
    const to2 = (n: any) => typeof n === 'number'
      ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      : (n ?? '');
    const fmtDate = (d: any) => {
      if (!d) return '';
      const dt = new Date(d); if (isNaN(dt.getTime())) return d;
      const y = dt.getFullYear(); const m = String(dt.getMonth()+1).padStart(2,'0'); const da = String(dt.getDate()).padStart(2,'0');
      return `${y}-${m}-${da}`;
    };
    const firstOr = (u: string) => (u && u.split(',')[0]) || '';
    const absUrl = (u: string) => {
      if (!u) return '';
      if (/^https?:\/\//i.test(u)) return u;
      const base = (environment.modifiedApiUrl || '').replace(/\/+$/, '');
      const path = ('' + u).replace(/^\/+/, '');
      return base ? `${base}/${path}` : u;
    };

    const sumQty = parts.reduce((s: number, p: any) => s + toNum(p?.purchaseQuantity ?? p?.quantity), 0);

    const rows = parts.map((p: any, i: number) => `
      <tr>
        <td>${i + 1}</td>
        <td>${p?.partNum ?? ''}</td>
        <td>${p?.partName ?? ''}</td>
        <td>${p?.partType ?? ''}</td>
        <td>${p?.partUOM ?? ''}</td>
        <td class="num">${to2(toNum(p?.purchaseQuantity ?? p?.quantity))}</td>
        <td>${p?.supplyName ?? ''}</td>
        <td>${p?.note ?? ''}</td>
        <td class="qr">${firstOr(p?.qrCode || '') ? `<img src="${absUrl(firstOr(p?.qrCode || ''))}" alt="qr" />` : ''}</td>
      </tr>`).join('');

    const style = `
      <style>
      @page { size: A4; margin: 10mm; }
      body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
      .sheet { width: 210mm; min-height: 297mm; padding: 12mm; margin: 0 auto; }
      .header { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; }
      .header .company { font-size: 12px; }
      .header .title { text-align: center; font-size: 24px; font-weight: 700; letter-spacing: 2px; }
      .hr { border-top: 2px solid #333; margin: 6px 0 10px; }
      .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px 24px; font-size: 12px; }
      table { width: 100%; border-collapse: collapse; margin-top: 10px; }
      th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
      th { background: #fafafa; }
      .num { text-align: right; }
      td.qr, th.qr { text-align: center; }
      td.qr img { width: 56px; height: 56px; object-fit: contain; }
      .footer { display: flex; justify-content: space-between; font-size: 12px; margin-top: 12px; border-top: 1px solid #333; padding-top: 6px; }
      </style>`;

    const now = new Date().toLocaleString('zh-CN');
    const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
      <div class="sheet">
        <div class="header">
          <div class="company">${order?.company ?? '公司抬头'}</div>
          <div class="title">采购需求单</div>
          <div></div>
        </div>
        <div class="hr"></div>
        <div class="info">
          <div><strong>单号：</strong>${order?.purchaseRequiredNum ?? ''}</div>
          <div><strong>申请人：</strong>${order?.purchaseManName ?? ''}</div>
          <div><strong>申请部门：</strong>${order?.departmentName ?? ''}</div>
          <div><strong>建议采购时间：</strong>${fmtDate(order?.advicePurchaseDate)}</div>
        </div>
        <table>
          <thead>
            <tr>
              <th style="width:44px;">序</th>
              <th style="width:140px;">物料编码</th>
              <th style="width:140px;">物料名称</th>
              <th style="width:140px;">规格/型号</th>
              <th style="width:60px;">单位</th>
              <th style="width:100px;" class="num">申请数量</th>
              <th style="width:140px;">建议供应商</th>
              <th style="width:160px;">备注</th>
              <th style="width:64px;" class="qr">二维码</th>
            </tr>
          </thead>
          <tbody>
            ${rows || '<tr><td colspan="9" style="text-align:center;">无明细</td></tr>'}
            <tr>
              <td colspan="5"><strong>合计数量</strong></td>
              <td class="num">${to2(sumQty)}</td>
              <td colspan="3"></td>
            </tr>
          </tbody>
        </table>
        <div class="footer">
          <div>打印时间：${now}</div>
          <div>单号：${order?.purchaseRequiredNum ?? ''}</div>
        </div>
      </div>
    </body></html>`;
    return html;
  }
  filter() {
    this.PurchaseService.getPurchaseRequirement(this.fifter).subscribe(
      (data: any) => {
        this.tableData = data.items;
        this.pager.total = data.totalCount;
        if (this.showDetailId) {
          this.showDetail(
            this.tableData.find(
              (item) => item.purchaseRequiredOrderId == this.showDetailId
            ),
            this.selectedRowIndex
          );
        }
      }
    );
  }
  filter2() {
    this.fifter.PageNumber = 1;
    this.PurchaseService.getPurchaseRequirement(this.fifter).subscribe(
      (data: any) => {
        this.tableData = data.items;
        this.tableData = data.items;
        this.pager.total = data.totalCount;
      }
    );
  }
  reset() {
    this.fifter = {
      PageSize: 20,
      PageNumber: 1,
      StartTime: '',
      EndTime: '',
      PurchaseRequiredNum: '',
      PartNumPartName: '',
      PurchaseManNumPurchaseManName: '',
      Status: '',
      isClosed: null,
    };
    this.date = [];
    this.filter();
  }
  creat() {
    this.Router.navigate(['/pages/purchase/purchase-require-add']);
  }
  edit(id: any) {
    this.Router.navigate(['/pages/purchase/purchase-require-edit/', id]);
  }
  delete(id?: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
      data: '',
      title: '删除',
      content: '删除后将无法恢复该数据！',
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (id) {
              this.PurchaseService.deletePurchaseRequirement([id]).subscribe(
                (res) => {
                  this.showToast('success', '成功', '删除成功');
                  this.filter();
                },
                (error) => {
                  if (error.status == 404) {
                    this.showToast('error', '失败', '服务器连接失败');
                  } else {
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
            } else {
              this.PurchaseService.deletePurchaseRequirement(
                this.checkedIds
              ).subscribe(
                (res) => {
                  this.showToast('success', '成功', '删除成功');
                  this.filter()
                  this.checkedIds = [];
                },
                (error: any) => {
                  this.SharedMethodService.handleError(error).subscribe(
                    (res) => {
                      this.showToast('error', '错误', res.content);
                    }
                  );
                }
              );
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  onRowCheckChange(
    checked: any,
    rowIndex: any,
    nestedIndex: any,
    rowItem: { $checked: any; $halfChecked: boolean }
  ){
    this.SharedMethodService.onRowCheckChange(
      checked,
      rowIndex,
      nestedIndex,
      rowItem,
      this.datatable
    );
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'purchaseRequiredOrderId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'purchaseRequiredNum'
    ).subscribe((data: any) => {
      this.checkedCodes = data;
    });
  } //获取选中行
  CheckedRows = [];
  getCheckedRowsData() {
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (data: any) => {
        this.CheckedRows = data;
      }
    );
  }
  cleared() {
    this.SharedMethodService.cleared(
      this.checkedIds,
      this.tableData,
      this.datatable
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //清空选中行
  pageIndexChange($event: any) {
    this.filter();
  } //切换页码
  pageSizeChange($event: any) {
    this.filter();
  } //改变每页显示数量
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  disApproval(num: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '600px',
      width: '400px',
      backdropCloseable: true,
      data: '',
      title: '不通过原因',
      content: DisApprovalReasonComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            console.log(results.modalContentInstance.reason);
            this.ReviewRolesService.GetApprovalNodeInstancesPaged(
              '审核中',
              num,
              1,
              1
            ).subscribe((res: any) => {
              if (res.items.length > 0) {
                this.ReviewRolesService.RejectNode(
                  res.items[0].approvalNodeId,
                  num,
                  results.modalContentInstance.reason
                ).subscribe(
                  (res) => {
                    this.showToast('success', '成功', '审批成功');
                    this.filter();
                  },
                  (error: any) => {
                    this.showToast(
                      'error',
                      '错误',
                      error.error || '网络连接错误'
                    );
                  }
                );
              } else {
                this.showToast('error', '错误', '没有需要审批的数据');
              }
            });
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  } //不通过
  // unApproval(id: any) {
  // this.PurchaseService.auditPurchaseRequirement('未开始审核', id).subscribe(
  //   (res) => {
  //     this.showToast('success', '成功', '反审核成功');
  //     this.filter();
  //   },
  //   (error: any) => {
  //     this.SharedMethodService.handleError(error).subscribe((res) => {
  //       this.showToast('error', '错误', res.content);
  //     });
  //   }
  // );
  // } //反审批
  closed(id: any) {
    this.PurchaseService.closePurchaseRequirement([id]).subscribe(
      (res) => {
        this.showToast('success', '成功', '结案成功');
      },
      (error: any) => {
        this.SharedMethodService.handleError(error).subscribe((res) => {
          this.showToast('error', '错误', res.content);
        });
      }
    );
  } //结案
  unClosed(id: any) {
    this.PurchaseService.closePurchaseRequirement([id]).subscribe(
      (res) => {
        this.showToast('success', '成功', '反结案成功');
      },
      (error: any) => {
        this.SharedMethodService.handleError(error).subscribe((res) => {
          this.showToast('error', '错误', res.content);
        });
      }
    );
  } //反结案
  allLog() {
    this.PurchaseService.GetAllPurchaseRequiredOrderLogs(1, 9999).subscribe(
      (data: any) => {
        const logData = data.items;
        const columns = [
          {
            field: '采购需求单号',
            header: '采购需求单号',
            fieldType: 'text',
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text',
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text',
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text',
          },
        ];
        this.results = this.drawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: { data: logData, columns: columns },
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {},
        });
      }
    );
  }
  GetLogsById(id: any) {
    this.PurchaseService.GetLogsByPurchaseRequiredOrderId(
      id,
      1,
      9999
    ).subscribe((data: any) => {
      const logData = data.items;
      const columns = [
        {
          field: '采购需求单号',
          header: '采购需求单号',
          fieldType: 'text',
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text',
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text',
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text',
        },
      ];
      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {},
      });
    });
  }
  transformPurchaseOrder() {
    if (this.CheckedRows.length == 0) {
      this.showToast('error', '错误', '请选择采购需求单');
      return;
    }
    if (this.CheckedRows.every((item) => item.status == '审核通过')) {
      this.dataSharingService
        .setData(this.CheckedRows)
        .subscribe((data: any) => {
          this.Router.navigate(['/pages/purchase/purchase-order-add'], {
            queryParams: {
              transform: true,
            },
          });
        });
    } else {
      this.showToast('error', '错误', '请选择已审核通过的采购需求单');
    }
  }
  downloadTemplate() {
    this.PurchaseService.exportPurchaseRequirementToExcelModel().subscribe(
      (data: any) => {
        const blob = new Blob([data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购需求单模版.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      }
    );
  }
  file: any;
  import(event: any) {
    this.file = event.target.files[0];
    this.PurchaseService.importPurchaseRequirementFromExcel(
      this.file
    ).subscribe((data: any) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '导入采购需求单.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
      this.filter();
    });
  }
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    this.fileInput2.nativeElement.click();
  }
  download() {
    this.PurchaseService.exportPurchaseRequirementToExcel().subscribe(
      (data: any) => {
        const blob = new Blob([data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购需求单.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      }
    );
  }
  fujian(rowitem: any, dialogtype?: string) {
    const results = this.dialogService.open({
      title: '附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: rowitem.files,
        type: '查看',
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  showDetail(data: any, rowIndex: any) {
    this.showDetailId = data.purchaseRequiredOrderId;
    (this.partDetail = data.purchaseRequiredOrderParts),
      (this.partDetailHeight = '75%');
    this.splitBarSize = '10px';
    this.selectedRowIndex = rowIndex;
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  dateChange($event: any) {
    this.fifter.StartTime = this.date[0]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
    this.fifter.EndTime = this.date[1]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
  }
  ClosePurchaseRequiredOrder(isClosed: boolean) {
    if (isClosed) {
      this.PurchaseService.ClosePurchaseRequiredOrder(
        this.CheckedRows.map((item) => item.purchaseRequiredOrderId),
        isClosed
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '结案成功');
          this.filter();
        },
        (error: any) => {
          this.showToast('error', '错误', error.error);
        }
      );
    } else {
      this.PurchaseService.ClosePurchaseRequiredOrder(
        this.CheckedRows.map((item) => item.purchaseRequiredOrderId),
        isClosed
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '反结案成功');
          this.filter();
        },
        (error: any) => {
          this.showToast('error', '错误', error.error);
        }
      );
    }
  }
  ClosePurchaseRequiredOrderPart(rowitem: any, isClosed: boolean) {
    if (isClosed) {
      this.PurchaseService.ClosePurchaseRequiredOrderPart(
        [rowitem.purchaseRequiredOrderPartId],
        isClosed
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '结案成功');
          this.filter();
        },
        (error: any) => {
          this.showToast('error', '错误', error.error);
        }
      );
    } else {
      this.PurchaseService.ClosePurchaseRequiredOrderPart(
        [rowitem.purchaseRequiredOrderPartId],
        isClosed
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '反结案成功');
          this.filter();
        },
        (error: any) => {
          this.showToast('error', '错误', error.error);
        }
      );
    }
  }
  launchReview() {
    const invalidStatus = this.CheckedRows.some(
      (row) => row.status === '审核通过' || row.status === '审核中'
    );
    if (invalidStatus) {
      this.showToast('error', '错误', '所选单据已发起审核');
      return;
    }
    if (this.checkedCodes.length < 1) {
      this.showToast('error', '错误', '请选择要发起审核的单据');
      return;
    }
    this.ReviewRolesService.StartApprovalFlow(
      '采购需求单审核流配置',
      this.checkedCodes
    ).subscribe(
      (res: any) => {
        this.showToast('success', '成功', res);
        this.filter();
        this.checkedIds = [];
        this.checkedCodes = [];
      },
      (error: any) => {
        this.showToast('error', '错误', error.error);
      }
    );
  }
  clickCode(code: string, type: string, status: string, dialogtype?: string) {
    let data = {
      code: code,
      type: type,
      disPlay: false,
    };
    const results = this.DialogService.open({
      id: 'custom',
      width: '90vw',
      maxHeight: '90vh',
      backdropCloseable: true,
      content: ReviewDocComponent,
      dialogtype: dialogtype,
      data:data,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '通过',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
            this.ReviewRolesService.ApproveNode(
              results.modalContentInstance.approvalNodeId,
              code
            ).subscribe((res: any) => {
              results.modalInstance.hide();
              this.showToast('success', '成功', '审批成功');
              this.filter();
            },error=>{
              this.showToast('error', '错误', error.error || '网络连接错误');
            }
          );
          }
          else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          cssClass: 'danger',
          text: '驳回',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
              console.log()
            if(results.modalContentInstance.reason){
              this.ReviewRolesService.RejectNode(
                results.modalContentInstance.approvalNodeId,
                code,
                results.modalContentInstance.reason
              ).subscribe(
                (res) => {
                  this.showToast('success', '成功', '审批成功');
                  results.modalInstance.hide();
                  this.filter();
                },
                (error: any) => {
                  this.showToast(
                    'error',
                    '错误',
                    error.error || '网络连接错误'
                  );
                }
              );
            }else{
              data.disPlay = true
              this.showToast('warn', '警告', '请填写驳回原因');
            }
          }else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getImagesArray2(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
    return urls;
  }
  selectsupply(rowItem:any, dialogtype?:string){
    const results = this.DialogService.open({
      id: 'Addselectsupply',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择供应商',
      content: SelectSupplierComponent,
      dialogtype: dialogtype,
      onClose: () => {

      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.PROPSupplyId = results.modalContentInstance.selectData.supplyId
            rowItem.supplyName = results.modalContentInstance.selectData.supplyChineseName
            rowItem.supplyNum = results.modalContentInstance.selectData.supplyNum
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
